import React, { useState } from 'react';
import axios from 'axios';
import { Menu, Icon, message } from 'antd';
import { Link, useLocation, useHistory } from 'react-router-dom';
import { useEffectOnce } from '../../utils/hooks';
import { Device } from '../deviceManagement/DeviceManagement';

const Navigation = () => {
  const { SubMenu } = Menu;
  let location = useLocation();
  let history = useHistory();

  let [devices, setDevices] = useState([] as Device[]);

  useEffectOnce(() => {
    axios
      .get('/devices')
      .then((response) => {
        setDevices(response.data);
      })
      .catch((error) => {
        if (error.response?.status === 401) {
          message.error('请先登录！');
          history.replace('/login');
        }
      });
  });

  return (
    <Menu
      selectedKeys={[location.pathname]}
      defaultOpenKeys={['monitors']}
      mode="inline"
      theme="dark"
    >
      <SubMenu
        key="monitors"
        title={
          <span>
            <Icon type="line-chart" />
            <span>实时监测</span>
          </span>
        }
      >
        {devices.map((device) => {
          return (
            <Menu.Item key={'/dacMonitor/' + device.deviceName}>
              <Link to={'/dacMonitor/' + device.deviceName} style={{ color: 'inherit' }}>
                {device.deviceName}
              </Link>
            </Menu.Item>
          );
        })}
      </SubMenu>
      <Menu.Item key="/devices">
        <Link to="/devices" style={{ color: 'inherit' }}>
          <Icon type="database" />
          <span>设备管理</span>
        </Link>
      </Menu.Item>
      <SubMenu
        key="personalCenter"
        title={
          <span>
            <Icon type="user" />
            <span>个人中心</span>
          </span>
        }
      >
        <Menu.Item key="/user">
          <Link to="/user" style={{ color: 'inherit' }}>
            修改密码
          </Link>
        </Menu.Item>
        <Menu.Item key="logout">
          <div
            onClick={() => {
              axios.post('/logout').then(() => {
                message.success('登出成功！');
                history.push('/login');
              });
            }}
          >
            退出登录
          </div>
        </Menu.Item>
      </SubMenu>
    </Menu>
  );
};

export default Navigation;
